package com.sdhs.analyze.service;

import com.alibaba.fastjson.JSONObject;
import com.sdhs.analyze.bean.InfoNodeStatus;
import com.sdhs.analyze.dao.InfoNodeStatusMapper;
import com.sdhs.analyze.utils.RedisUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class InfoNodeStatusService {
    @Autowired
    private InfoNodeStatusMapper infoNodeStatusMapper;
    @Autowired
    private RedisUtil redisUtil;

    @Transactional
    public void insert(InfoNodeStatus record) {
        infoNodeStatusMapper.insert(record);
    }

    @Transactional
    public void delete(String nodeId, String nodeType) {
        infoNodeStatusMapper.delete(nodeId, nodeType);
    }

    public Map<String, InfoNodeStatus> selectByNodeType() {
        String jsonString = redisUtil.get("dic_node_type");
        Map<String, InfoNodeStatus> map;
        if (StringUtils.isNotBlank(jsonString)) {
            map = (Map) JSONObject.parse(jsonString);
            for (Map.Entry<String, InfoNodeStatus> element : map.entrySet()) {
                Object tmp = element.getValue();
                tmp = JSONObject.parseObject(JSONObject.toJSONString(tmp), InfoNodeStatus.class);
                map.put(element.getKey(), (InfoNodeStatus) tmp);
            }
        } else {
            map = new HashMap<>();
            List<InfoNodeStatus> list = infoNodeStatusMapper.selectByNodeType();
            for (InfoNodeStatus node : list) {
                map.put(node.getNodeType(), node);
            }
            redisUtil.setEx("dic_node_type", JSONObject.toJSONString(map), 10, TimeUnit.MINUTES);
        }
        return map;
    }

    public Integer selectMaxNum(String nodeId, String nodeType) {
        return infoNodeStatusMapper.selectMaxNum(nodeId, nodeType);
    }

    public Integer selectMinNum(String nodeId, String nodeType) {
        return infoNodeStatusMapper.selectMinNum(nodeId, nodeType);
    }
}
